<?php

namespace app\admin\controller\comment;

use app\common\controller\Backend;
use app\common\model\CommentRule;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 点评规则
 *
 * @icon fa fa-circle-o
 */
class Rule extends Backend
{

    /**
     * CommentRule模型对象
     * @var \app\common\model\CommentRule
     */
    protected $model = null;
    protected $schoolLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CommentRule;

        $this->assign('behaviorCategoryTypeData', CommentRule::$behaviorCategoryTypeList);
        $this->assign('timeTypeData', CommentRule::$timeTypeList);
        $this->assign('weekData', CommentRule::$weekList);


//        $school = $this->model->whereIn('school_id', $this->auth->getSchoolIds())
//            ->where('time_type', CommentRule::CUSTOMER)
//            ->group('school_id')
//            ->column('school_id,min(customer_start_time) customer_start_time,max(customer_end_time) customer_end_time', 'school_id');
//
//        $week_rule = $this->model->whereIn('school_id', $this->auth->getSchoolIds())
//            ->where('time_type', CommentRule::WEEK)
//            ->field('school_id,week')
//            ->select();
//        foreach ($week_rule as $key => $value) {
//            if (!isset($school[$value['school_id']]['week'])) {
//                $school[$value['school_id']]['week'] = explode(',', $value['week']);
//            } else {
//                $school[$value['school_id']]['week'] = array_merge($school[$value['school_id']]['week'], explode(',', $value['week']));
//            }
//        }
//
//        dd($school);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model->with('school')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['note'])->toArray();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['start_time'] >= $params['end_time']) {
                    $this->error('结束时间必须大于开始时间');
                }

                switch ($params['time_type']) {
                    case CommentRule::WEEK:
                        $params['customer_start_time'] = 0;
                        $params['customer_end_time'] = 0;
                        if (!array_filter($params['week'])) {
                            $this->error('请选择日期');
                        }

                        $rule = $this->model
                            ->where('behavior_category_type', $params['behavior_category_type'])
                            ->where('time_type', CommentRule::WEEK)
                            ->where(function ($query) use ($params) {
                                foreach ($params['week'] as $key => $value) {
                                    $query->whereOr("FIND_IN_SET($value, week)");
                                }
                            })
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['start_time'])->where('end_time', '>=', $params['start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['end_time'])->where('end_time', '>=', $params['end_time']);
                                });
                            })
                            ->where('school_id', $params['school_id'])
                            ->find();


                        if ($rule) {
                            $week = array_intersect($params['week'], explode(',', $rule->week));
                            $attr = [];
                            foreach ($week as $key => $value) {
                                if (isset(CommentRule::$weekList[$value])) {
                                    $attr[] = CommentRule::$weekList[$value];
                                }
                            }
                            $this->error('「'.implode(',', $attr). '」 时间点有重合');
                        }

                        break;
                    case CommentRule::CUSTOMER:
                        if (!$params['customer']) {
                            $this->error('请选择时间段');
                        }
                        $params['week'] = '';
                        list($params['customer_start_time'], $params['customer_end_time']) = array_map(function($value){
                            return strtotime($value);
                        }, explode(' - ', $params['customer']));

                        if ($params['customer_start_time'] >= $params['customer_end_time']) {
                            $this->error('时间段选择有误');
                        }

                        $rule = $this->model
                            ->where('behavior_category_type', $params['behavior_category_type'])
                            ->where('time_type', CommentRule::CUSTOMER)
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('customer_start_time', '<=', $params['customer_start_time'])->where('customer_end_time', '>=', $params['customer_start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('customer_end_time', '<=', $params['customer_end_time'])->where('customer_end_time', '>=', $params['customer_end_time']);
                                });
                            })
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['start_time'])->where('end_time', '>=', $params['start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['end_time'])->where('end_time', '>=', $params['end_time']);
                                });
                            })
                            ->where('school_id', $params['school_id'])
                            ->find();

                        if ($rule) {
                            $this->error('该时间段内时间点有重合');
                        }

                        break;
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['start_time'] >= $params['end_time']) {
                    $this->error('结束时间必须大于开始时间');
                }

                switch ($params['time_type']) {
                    case CommentRule::WEEK:
                        $params['customer_start_time'] = 0;
                        $params['customer_end_time'] = 0;
                        if (!array_filter($params['week'])) {
                            $this->error('请选择日期');
                        }

                        $rule = $this->model
                            ->where('id', '<>', $row->id)
                            ->where('behavior_category_type', $params['behavior_category_type'])
                            ->where('time_type', CommentRule::WEEK)
                            ->where(function ($query) use ($params) {
                                foreach ($params['week'] as $key => $value) {
                                    $query->whereOr("FIND_IN_SET($value, week)");
                                }
                            })
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['start_time'])->where('end_time', '>=', $params['start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['end_time'])->where('end_time', '>=', $params['end_time']);
                                });
                            })
                            ->where('school_id', $params['school_id'])
                            ->find();


                        if ($rule) {
                            $week = array_intersect($params['week'], explode(',', $rule->week));
                            $attr = [];
                            foreach ($week as $key => $value) {
                                if (isset(CommentRule::$weekList[$value])) {
                                    $attr[] = CommentRule::$weekList[$value];
                                }
                            }
                            $this->error('「'.implode(',', $attr). '」 时间点有重合');
                        }

                        break;
                    case CommentRule::CUSTOMER:
                        if (!$params['customer']) {
                            $this->error('请选择时间段');
                        }
                        $params['week'] = '';
                        list($params['customer_start_time'], $params['customer_end_time']) = array_map(function($value){
                            return strtotime($value);
                        }, explode(' - ', $params['customer']));

                        if ($params['customer_start_time'] >= $params['customer_end_time']) {
                            $this->error('时间段选择有误');
                        }

                        $rule = $this->model
                            ->where('id', '<>', $row->id)
                            ->where('behavior_category_type', $params['behavior_category_type'])
                            ->where('time_type', CommentRule::CUSTOMER)
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('customer_start_time', '<=', $params['customer_start_time'])->where('customer_end_time', '>=', $params['customer_start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('customer_end_time', '<=', $params['customer_end_time'])->where('customer_end_time', '>=', $params['customer_end_time']);
                                });
                            })
                            ->where(function ($query) use ($params) {
                                $query->where(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['start_time'])->where('end_time', '>=', $params['start_time']);
                                })->whereOr(function ($q) use ($params) {
                                    $q->where('start_time', '<=', $params['end_time'])->where('end_time', '>=', $params['end_time']);
                                });
                            })
                            ->where('school_id', $params['school_id'])
                            ->find();

                        if ($rule) {
                            $this->error('该时间段内时间点有重合');
                        }

                        break;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
